angular.module('app').controller('detailCtrl', 
['$scope', '$rootScope', 'stateV', 'http','$state',
function($scope, $rootScope,stateV,http,$state) 
{
	$rootScope.header = false;
	$scope.comment = {pid:'', content:'', num:0, ok:true};

	function ngInit(){
		// $scope.detail = stateV.get();
		// $scope.detail = http.cacheUtil.getObject('detailPost');
		$scope.comment.pid = $state.params.pid;

		http.post(globalConfig.web + "/posts/detail", {pid:$state.params.pid}, function(data, status){
			$scope.detail = data;
		})

		http.get(globalConfig.web + "/home/source?source="+$scope.detail.pid, function(){});

		// 获取评论内容列表
		http.get(globalConfig.web+"/comment/query?pid="+$scope.comment.pid, function(data, status){
			$scope.commentList = data;
			$scope.comment.num = data.length;
		})
	}

	$scope.demo = function(url){
		if(''==url){
			alert('暂无演示文件')
		}else{
			window.open(url)
		}
	}

	$scope.buy = function(){
		var payUrl = globalConfig.web + "/order/new";
		http.post(payUrl, {pid:$scope.detail.pid}, function(data, status){
			if(status==200){
				$state.go('order', {orderid: data.orderid})
			}else if(status==403){
				alert("订单信息错误")
			}
		})
	}

	$scope.reply = function(){
		if($scope.comment.content.trim()==''){
			alert('内容不能为空')
			return false;
		}
		if(!$scope.comment.ok){
			alert('发表过于频繁稍后再试')
			return false;
		}
		var reqUrl = globalConfig.web + "/comment/add";
		http.post(reqUrl, $scope.comment, function(data, status){
			$scope.commentList = data;
			$scope.comment.num = data.length;
			$scope.comment.ok = false;
			forbit(10)
		})
	}

	function forbit(times){
    	if(!times||isNaN(parseInt(times)))return;
    	var args = arguments;
    	var self = this;
     	setTimeout(function(){
     		args.callee.call(self,--times);
     		if(times==0){
     			$scope.comment.ok = true;
     		}
     	},1000); 	
	}

	$scope.detail = function(data){
		http.cacheUtil.setObject('detailPost', data);
		$state.go('detail')
	}

	ngInit();
	
}]);